package main

import (
	"bytes"
	"fmt"
	"strconv"
	"strings"
	"unicode/utf8"
)

func main() {
	s := "Hello, 世界"
	fmt.Println(len(s))                    // "13"--字节长度
	fmt.Println(utf8.RuneCountInString(s)) // "9" --unicode码字符数

	for i := 0; i < len(s); {
		r, size := utf8.DecodeRuneInString(s[i:])
		fmt.Printf("%d\t%c\n", i, r)
		i += size
	}
	fmt.Printf("%d\n", 'A')
	for i, r := range "Hello, 世界" {
		fmt.Printf("%d\t%q\t%d\n", i, r, r)
	}

	n := 0
	for range s {
		n++
	}
	fmt.Println(n)
	fmt.Println(utf8.RuneCountInString(s))

	// "program" in Japanese katakana
	s1 := "プログラム"
	fmt.Printf("% x\n", s1) // "e3 83 97 e3 83 ad e3 82 b0 e3 83 a9 e3 83 a0"
	r := []rune(s1)
	fmt.Printf("%x\n", r)  // "[30d7 30ed 30b0 30e9 30e0]"
	fmt.Println(string(r)) // "プログラム"
	//fmt.Println(string(65))     // "A", not "65"
	//fmt.Println(string(0x4eac)) // "京"
	//fmt.Println(string(1234567)) // "�"
	fmt.Println(basename("a/b/c.go"))  // "c"
	fmt.Println(basename("c.d.go"))    // "c.d"
	fmt.Println(basename("abc"))       // "abc"
	fmt.Println(basename1("a/b/c.go")) // "c"
	fmt.Println(comma("12356891646"))
	fmt.Println(strings.Fields("hello hh   hhd"))
	fmt.Println(intsToString([]int{1, 2, 3})) // "[1, 2, 3]"
	x := 123
	y := fmt.Sprintf("%d", x)
	fmt.Println(y, strconv.Itoa(x)) // "123 123
	fmt.Printf("x=%b", x)           // "x=1111011"

}

// basename removes directory components and a .suffix.
// e.g., a => a, a.go => a, a/b/c.go => c, a/b.c.go => b.c
func basename(s string) string {
	// Discard last '/' and everything before.
	for i := len(s) - 1; i >= 0; i-- {
		if s[i] == '/' {
			s = s[i+1:]
			break
		}
	}
	// Preserve everything before last '.'.
	for i := len(s) - 1; i >= 0; i-- {
		if s[i] == '.' {
			s = s[:i]
			break
		}
	}
	return s
}

//使用strings.LastIndex库函数简化
func basename1(s string) string {
	slash := strings.LastIndex(s, "/") // -1 if "/" not found
	s = s[slash+1:]
	if dot := strings.LastIndex(s, "."); dot >= 0 {
		s = s[:dot]
	}
	return s
}

// comma inserts commas in a non-negative decimal integer string.，每三个字符加个逗号
func comma(s string) string {
	n := len(s)
	if n <= 3 {
		return s
	}
	return comma(s[:n-3]) + "," + s[n-3:]
}

//bytes.Buffer
func intsToString(values []int) string {
	var buf bytes.Buffer
	buf.WriteByte('[')
	for i, v := range values {
		if i > 0 {
			buf.WriteString(", ")
		}
		fmt.Fprintf(&buf, "%d", v)
	}
	buf.WriteByte(']')
	return buf.String()
}
